package com.qfmy.common.utils;
import com.qfmy.common.exception.BaseException;
import com.qfmy.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.common.utils
 * @date 2025/4/13
 * @description Jwt工具类
 */
@SuppressWarnings("all")
public class JwtUtil {
    /**
     * access token有效期
     */
    public static long accessTokenExpiration = 60 * 60 * 1000L;
    /**
     * refresh token有效期
     */
    public static long refreshTokenExpiration = 7 * 24 * 60 * 60 * 1000L;

    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    /**
     * 生成access token
     * @param phone
     * @param username
     * @param id
     * @return
     */
    public static String generateAccessToken(String phone, String username, Long id) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("phone", phone);
        claims.put("userId", id);
        claims.put("username", username);
        String token = Jwts.builder()
                .setSubject("Login_INFO")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + accessTokenExpiration))
                .setClaims(claims)
                .signWith(tokenSignKey, SignatureAlgorithm.HS256)
                .compact();
        return token;
    }

    /**
     * 生成refresh token
     * @param phone
     * @param username
     * @param id
     * @return
     */
    public static String generateRefreshToken(String phone, String username, Long id) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("phone", phone);
        claims.put("userId", id);
        claims.put("username", username);
        String token = Jwts.builder()
                .setSubject("Login_INFO")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + refreshTokenExpiration))
                .setClaims(claims)
                .signWith(tokenSignKey, SignatureAlgorithm.HS256)
                .compact();
        return token;
    }

    /**
     * 解析token获取用户信息
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        try {
            JwtParser build = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
            Jws<Claims> claimsJws = build.parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            return body;
        } catch (ExpiredJwtException e) {
            throw new BaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    /**
     * 刷新access token
     * @param refreshToken
     * @return
     */
    public static String refreshToken(String refreshToken) {
        Claims claims = parseToken(refreshToken);
        String phone = (String) claims.get("phone");
        String username = (String) claims.get("username");
        Long id = (Long) claims.get("userId");
        return generateAccessToken(phone, username, id);
    }
}